package edu.mju.controller;

import edu.mju.entity.*;
import edu.mju.service.ICompanyService;
import edu.mju.service.IRoutesService;
import edu.mju.service.ISpotListService;
import edu.mju.service.IUserService;
import edu.mju.service.impl.CompanyServiceImpl;
import edu.mju.service.impl.RoutesServiceImpl;
import edu.mju.service.impl.SpotListServiceImpl;
import edu.mju.service.impl.UserServiceImpl;
import edu.mju.util.ExcelUtil;
import edu.mju.util.Pager;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author:wyp
 * @Date:2020/5/30 22:54
 */
@WebServlet("/download")
public class ExportController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");
        System.out.println("doget:"+method);
        if("downUser".equals(method)){
            downUser(req,resp);
        }else if("downSpot".equals(method)){
            downSpot(req,resp);
        }else if("downCompany".equals(method)){
            downCompany(req,resp);
        }else if("downSearchCompany".equals(method)){
            downSearchCompany(req,resp);
        }else if("downSearchUser".equals(method)){
            downSearchUser(req,resp);
        }else if("downRoutes".equals(method)){
            downRoutes(req,resp);
        }else if("downSearcRoutes".equals(method)){
            downSearcRoutes(req,resp);
        }else if("downCompanyRoutes".equals(method)){
            downCompanyRoutes(req,resp);
        }else if("downOrder".equals(method)){
            downOrder(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    /** 旅游公司>旅游线路
     *  打印订单用户列表
     * @param req
     * @param resp
     */
    private void downOrder(HttpServletRequest req, HttpServletResponse resp) {

        Pager pager = (Pager) req.getSession().getAttribute("pager");
        List<Object> list = pager.getData();

        //excel标题
        String[] title = {"订单编号", "用户编号", "用户名",
                "性别", "联系电话", "预约线路"};

        //excle文件名
        String fileName = "预约客户信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "预约客户信息表";

        //这里list由于是拼接的 所以list需要/2
        String[][] content = new String[list.size()/2][title.length];
        for (int i = 0; i < list.size()/2; i++) {
            content[i] = new String[title.length];
            Order order = (Order) list.get(2*i);
            User user = (User)list.get(2*i+1);
            content[i][0] = String.valueOf(order.getOrderId());
            content[i][1] = String.valueOf(order.getUserId());
            content[i][2] = user.getUserName();
            if(user.getUserSex()==0){
                content[i][3] = "女";
            }else if(user.getUserSex()==1){
                content[i][3] = "男";
            }
            content[i][4] = user.getUserTel();
            content[i][5] = String.valueOf(order.getTouristId());
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 旅游公司
     *  打印线路表格
     * @param req
     * @param resp
     */
    private void downCompanyRoutes(HttpServletRequest req, HttpServletResponse resp){

        Pager pager = (Pager) req.getSession().getAttribute("pager");
        List<Object> routesList = pager.getData();

        //excel标题
        String[] title ={"线路ID","旅游景点","餐饮",
                "住宿","交通","费用","负责人电话",
                "当前预约人数","最多人数","封面图片"};

        //excle文件名
        String fileName= "线路信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "线路信息表";

        String [][] content = new String[routesList.size()][title.length];
        for(int i = 0 ;i<routesList.size();i++){
            content[i] = new String[title.length];
            TouristRoutes route = (TouristRoutes) routesList.get(i);
            content[i][0] = String.valueOf(route.getTouristId());
            content[i][1] = route.getAllSpot();
            content[i][2] = route.getRestaurant();
            content[i][3] = route.getLive();
            content[i][4] = route.getTraffice();
            content[i][5] = String.valueOf(route.getTouristPrice());
            content[i][6] = route.getTel();
            content[i][7] = String.valueOf(route.getNowPeople());
            content[i][8] = String.valueOf(route.getMaxPeople());
            content[i][9] = route.getRoutesImg();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  打印查询的线路表格
     * @param req
     * @param resp
     */
    private void downSearcRoutes(HttpServletRequest req, HttpServletResponse resp){

        Pager pager = (Pager) req.getSession().getAttribute("pager");
        List<Object> routesList = pager.getData();

        //excel标题
        String[] title ={"线路ID","旅游景点","餐饮",
                "住宿","交通","费用","负责人电话",
                "当前预约人数","最多人数","封面图片"};

        //excle文件名
        String fileName= "查询的线路信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "查询的线路信息表";

        String [][] content = new String[routesList.size()][title.length];
        for(int i = 0 ;i<routesList.size();i++){
            content[i] = new String[title.length];
            TouristRoutes route = (TouristRoutes) routesList.get(i);
            content[i][0] = String.valueOf(route.getTouristId());
            content[i][1] = route.getAllSpot();
            content[i][2] = route.getRestaurant();
            content[i][3] = route.getLive();
            content[i][4] = route.getTraffice();
            content[i][5] = String.valueOf(route.getTouristPrice());
            content[i][6] = route.getTel();
            content[i][7] = String.valueOf(route.getNowPeople());
            content[i][8] = String.valueOf(route.getMaxPeople());
            content[i][9] = route.getRoutesImg();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  打印线路表格
     * @param req
     * @param resp
     */
    private void downRoutes(HttpServletRequest req, HttpServletResponse resp){
        IRoutesService routesService = new RoutesServiceImpl();
        //获取数据
        TouristRoutes routes = new TouristRoutes();
        Pager pager = routesService.pagernate(1,999,routes);
        List<Object> routesList = pager.getData();

        //excel标题
        String[] title ={"线路ID","旅游景点","餐饮",
                "住宿","交通","费用","负责人电话",
                "当前预约人数","最多人数","封面图片"};

        //excle文件名
        String fileName= "线路信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "线路信息表";

        String [][] content = new String[routesList.size()][title.length];
        for(int i = 0 ;i<routesList.size();i++){
            content[i] = new String[title.length];
            TouristRoutes route = (TouristRoutes) routesList.get(i);
            content[i][0] = String.valueOf(route.getTouristId());
            content[i][1] = route.getAllSpot();
            content[i][2] = route.getRestaurant();
            content[i][3] = route.getLive();
            content[i][4] = route.getTraffice();
            content[i][5] = String.valueOf(route.getTouristPrice());
            content[i][6] = route.getTel();
            content[i][7] = String.valueOf(route.getNowPeople());
            content[i][8] = String.valueOf(route.getMaxPeople());
            content[i][9] = route.getRoutesImg();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  打印查询的旅游公司表格
     * @param req
     * @param resp
     */
    private void downSearchCompany(HttpServletRequest req, HttpServletResponse resp){
        //获取数据
        Pager pager =(Pager) req.getSession().getAttribute("pager");
        List<Object> company = pager.getData();

        //excel标题
        String[] title ={"公司ID","公司名","用户ID"
        };

        //excle文件名
        String fileName= "查询的公司信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "查询的公司信息表";

        String [][] content = new String[company.size()][3];
        for(int i = 0 ;i<company.size();i++){
            content[i] = new String[title.length];
            TouristCompany getCompany = (TouristCompany) company.get(i);
            content[i][0] = String.valueOf(getCompany.getCompanyId());
            content[i][1] = getCompany.getCompanyName();
            content[i][2] = String.valueOf(getCompany.getUserId());
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  打印旅游公司表格
     * @param req
     * @param resp
     */
    private void downCompany(HttpServletRequest req, HttpServletResponse resp){
        ICompanyService companyService = new CompanyServiceImpl();
        //获取数据
        TouristCompany touristCompany = new TouristCompany();
        Pager pager = companyService.pagernate(1,999,touristCompany);
        List<Object> company = pager.getData();

        //excel标题
        String[] title ={"公司ID","公司名","用户ID"
                };

        //excle文件名
        String fileName= "公司信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "公司信息表";

        String [][] content = new String[company.size()][7];
        for(int i = 0 ;i<company.size();i++){
            content[i] = new String[title.length];
            TouristCompany getCompany = (TouristCompany) company.get(i);
            content[i][0] = String.valueOf(getCompany.getCompanyId());
            content[i][1] = getCompany.getCompanyName();
            content[i][2] = String.valueOf(getCompany.getUserId());
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     *  打印景点表格
     * @param req
     * @param resp
     */
    private void downSpot(HttpServletRequest req, HttpServletResponse resp){
        ISpotListService spotListService = new SpotListServiceImpl();
        //获取数据
        ScenicSpot scenicSpot = new ScenicSpot();
        Pager pager = spotListService.pagernate(1,999,scenicSpot);
        List<Object> spot = pager.getData();

        //excel标题
        String[] title ={"景点ID","景点","地址"
                ,"游览项目","价格","开放时间"
                ,"图片地址"};

        //excle文件名
        String fileName= "景点信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "景点信息表";

        String [][] content = new String[spot.size()][7];
        for(int i = 0 ;i<spot.size();i++){
            content[i] = new String[title.length];
            ScenicSpot getSpot = (ScenicSpot) spot.get(i);
            content[i][0] = String.valueOf(getSpot.getSpotId());
            content[i][1] = getSpot.getSpotName();
            content[i][2] = getSpot.getSpotPlace();
            content[i][3] = getSpot.getSpotItem();
            content[i][4] = String.valueOf(getSpot.getSpotPrice());
            content[i][5] = getSpot.getSpotOpenTime();
            content[i][6] = getSpot.getSpotImgUrl();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  打印查询的用户表格
     * @param req
     * @param resp
     */
    private void downSearchUser(HttpServletRequest req, HttpServletResponse resp){
        IUserService userService = new UserServiceImpl();
        //获取数据
        User user = new User();
        Pager pager = (Pager) req.getSession().getAttribute("pager");
        List<Object> users = pager.getData();

        //excel标题
        String[] title ={"用户ID","用户名","密码"
                ,"联系电话","加密","性别"
                ,"身份"};

        //excle文件名
        String fileName= "查询的用户信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "查询的用户信息表";

        String [][] content = new String[users.size()][7];
        for(int i = 0 ;i<users.size();i++){
            content[i] = new String[title.length];
            User getuser = (User) users.get(i);
            content[i][0] = String.valueOf(getuser.getUserId());
            content[i][1] = getuser.getUserName();
            content[i][2] = getuser.getUserPassword();
            content[i][3] = getuser.getUserTel();
            content[i][4] = getuser.getUsersalt();
            content[i][5] = String.valueOf(getuser.getUserSex());
            content[i][6] = getuser.getUserRole();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  打印用户表格
     * @param req
     * @param resp
     */
    private void downUser(HttpServletRequest req, HttpServletResponse resp){
        IUserService userService = new UserServiceImpl();
        //获取数据
        User user = new User();
        Pager pager = userService.pagernate(1,999,user);
        List<Object> users = pager.getData();

        //excel标题
        String[] title ={"用户ID","用户名","密码"
                ,"联系电话","加密","性别"
                ,"身份"};

        //excle文件名
        String fileName= "用户信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "用户信息表";

        String [][] content = new String[users.size()][7];
        for(int i = 0 ;i<users.size();i++){
            content[i] = new String[title.length];
            User getuser = (User) users.get(i);
            content[i][0] = String.valueOf(getuser.getUserId());
            content[i][1] = getuser.getUserName();
            content[i][2] = getuser.getUserPassword();
            content[i][3] = getuser.getUserTel();
            content[i][4] = getuser.getUsersalt();
            content[i][5] = String.valueOf(getuser.getUserSex());
            content[i][6] = getuser.getUserRole();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);

        //响应到客户端
        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送响应流方法
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
